import eventBus from '../utils/eventBus'
import Util from '@antv/g6/src/util'
export default {
  getEvents() {
    return {
      'node:contextmenu': 'onContextmenu',
      mousedown: 'onMousedown',
      'canvas:click': 'onCanvasClick'
    }
  },
  onContextmenu(e) {
    const self = this
    const item = e.item
    const graph = self.graph
    const autoPaint = graph.get('autoPaint')
    graph.setAutoPaint(false)
    const selectedEdges = graph.findAllByState('edge', 'selected')
    // 可以把数组对象中的每个元素执行一次后面的方法
    Util.each(selectedEdges, edge => {
      graph.setItemState(edge, 'selected', false)
    })
    if (!self.keydown || !self.multiple) {
      const selected = graph.findAllByState('node', 'selected')
      // 把所有不属于当前选中的置为false
      Util.each(selected, node => {
        if (node !== item) {
          graph.setItemState(node, 'selected', false)
        }
      })
    }
    if (item.hasState('selected')) {
      if (self.shouldUpdate.call(self, e)) {
        graph.setItemState(item, 'selected', false)
      }

      eventBus.$emit('nodeselectchange', { target: item, select: false })
    } else {
      // 判断是否有交互效果发生
      if (self.shouldUpdate.call(self, e)) {
        graph.setItemState(item, 'selected', true)
      }
      eventBus.$emit('nodeselectchange', { target: item, select: true })
    }
    graph.setAutoPaint(autoPaint)
    graph.paint()
    eventBus.$emit('contextmenuClick', e)
  },
  onMousedown(e) {
    eventBus.$emit('mousedown', e)
  },
  onCanvasClick(e) {
    eventBus.$emit('canvasClick', e)
  }
}
